package com.java110.mall.chain.supplier.adaper.llk;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.java110.mall.chain.supplier.ISupplierAdapter;
import com.java110.core.client.RestTemplate;
import com.java110.core.factory.GenerateCodeFactory;
import com.java110.dto.area.AreaDto;
import com.java110.dto.chain.ChainSupplierProductDto;
import com.java110.dto.chain.ChainProductDto;
import com.java110.dto.chain.ChainProductValueDto;
import com.java110.dto.chain.ChainSupplierDto;
import com.java110.dto.chain.ChainSupplierCatalogDto;
import com.java110.dto.file.FileDto;
import com.java110.dto.file.FileRelDto;
import com.java110.dto.housekeeping.HousekeepingServDto;
import com.java110.dto.product.ProductCategoryDto;
import com.java110.dto.product.ProductDto;
import com.java110.dto.product.ProductPriceRuleDto;
import com.java110.dto.product.ProductSpecValueDto;
import com.java110.dto.shop.ShopHouseDto;
import com.java110.dto.storeOrder.StoreOrderDto;
import com.java110.dto.storeOrder.StoreOrderAddressDto;
import com.java110.dto.storeOrder.StoreOrderCartDto;
import com.java110.intf.cart.IStoreOrderAddressInnerServiceSMO;
import com.java110.intf.cart.IStoreOrderCartInnerServiceSMO;
import com.java110.intf.chain.IChainSupplierCatalogV1InnerServiceSMO;
import com.java110.intf.user.IAreaInnerServiceSMO;
import com.java110.intf.system.IFileInnerServiceSMO;
import com.java110.intf.system.IFileRelInnerServiceSMO;
import com.java110.intf.goods.*;
import com.java110.intf.shop.IShopHouseInnerServiceSMO;
import com.java110.po.file.FileRelPo;
import com.java110.po.product.ProductCategoryPo;
import com.java110.po.product.ProductPo;
import com.java110.po.product.ProductSpecDetailPo;
import com.java110.po.product.ProductSpecPo;
import com.java110.po.product.ProductDetailPo;
import com.java110.po.product.ProductServKeywordPo;
import com.java110.po.product.ProductSpecValuePo;
import com.java110.po.shop.ShopHousePo;
import com.java110.po.storeOrder.StoreOrderCartPo;
import com.java110.utils.log.LoggerEngine;
import com.java110.utils.util.Assert;
import com.java110.utils.util.StringUtil;
import com.java110.vo.ResultVo;
import com.jxhh.ApiClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import sun.misc.BASE64Encoder;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 联联看 供应商 对接适配类
 */
@Component
public class LlkSupplierAdapter implements ISupplierAdapter {

    private final static Logger logger = LoggerFactory.getLogger(LoggerEngine.class);
    //查询产品列表
    public static final String URL_GET_PRODUCTS = "/ll/api/product/queryProductList";
    //查询产品详情列表
    public static final String URL_GET_PRODUCTDETAIL = "/ll/api/product/queryProductByCondition";
    //查询产品物流信息
    public static final String URL_GET_ORDEREXPRESS = "/ll/api/orderDetail/queryOrderExpress";
    //图文文案1
    public static final String URL_GET_PRODUCTHTML = "/ll/api/product//detail/html";
    //图文文案2
    public static final String URL_GET_PRODUCTHTML2 = "/ll/api/product/detail/v2/html";
    //查询产品分类
    public static final String URL_GET_PRODUCTCATEGORY = "/ll/api/product/queryProductCategory";
    //校验产品下单
    public static final String URL_GET_CHECKCREATEORDER = "/ll/api/channelOrder/checkCreateOrder";
    //产品下单
    public static final String URL_CREATEORDER = "/ll/api/channelOrder/createOrder";

    @Autowired
    private IChainSupplierCatalogV1InnerServiceSMO chainSupplierCatalogV1InnerServiceSMO;

    @Autowired
    public RestTemplate outRestTemplate;


    @Autowired
    private IProductInnerServiceSMO productInnerServiceSMOImpl;

    @Autowired
    private IStoreOrderAddressInnerServiceSMO storeOrderAddressInnerServiceSMOImpl;

    @Autowired
    private IAreaInnerServiceSMO areaInnerServiceSMO;

    @Autowired
    private IStoreOrderCartInnerServiceSMO storeOrderCartInnerServiceSMOImpl;

    @Autowired
    private IProductCategoryInnerServiceSMO productCategoryInnerServiceSMOImpl;

    @Autowired
    private IShopHouseInnerServiceSMO shopHouseInnerServiceSMOImpl;

    @Autowired
    private IProductSpecInnerServiceSMO productSpecInnerServiceSMOImpl;

    @Autowired
    private IProductSpecDetailInnerServiceSMO productSpecDetailInnerServiceSMOImpl;

    @Autowired
    private IProductSpecValueInnerServiceSMO productSpecValueInnerServiceSMOImpl;

    @Autowired
    private IProductDetailInnerServiceSMO productDetailInnerServiceSMOImpl;

    @Autowired
    private IProductServKeywordInnerServiceSMO productServKeywordInnerServiceSMOImpl;

    @Autowired
    private IFileInnerServiceSMO fileInnerServiceSMOImpl;

    @Autowired
    private IFileRelInnerServiceSMO fileRelInnerServiceSMOImpl;

    @Autowired
    private IProductPriceRuleV1InnerServiceSMO productPriceRuleV1InnerServiceSMOImpl;

//    @Autowired
//    private IBuildingOwnerV1InnerServiceSMO buildingOwnerV1InnerServiceSMOImpl;


    @Override
    public ResultVo validateChainOrder(StoreOrderDto storeOrderDto, List<StoreOrderCartDto> storeOrderCartDtos, ChainSupplierDto chainSupplierDto) throws Exception {
        //获取订单收货地址
        StoreOrderAddressDto storeOrderAddressDto = new StoreOrderAddressDto();
        storeOrderAddressDto.setOrderId(storeOrderDto.getOrderId());
        List<StoreOrderAddressDto> userAddressDtos = storeOrderAddressInnerServiceSMOImpl.queryStoreOrderAddresss(storeOrderAddressDto);
        Assert.listOnlyOne(userAddressDtos, "未找到收货人信息");
        StoreOrderAddressDto addressDto = userAddressDtos.get(0);
        for (StoreOrderCartDto storeOrderCartDto : storeOrderCartDtos) {//校验供应链商品
            JSONObject param = new JSONObject();
            param.put("productId", storeOrderCartDto.getProductId());
            JSONObject returnData = JSONObject.parseObject(LlkFactory.post(URL_GET_PRODUCTDETAIL, param, chainSupplierDto, outRestTemplate));
            String isneedId = returnData.getString("orderShowIdCard");
            if (isneedId.equals("1")) {//需要身份证信息
//                OwnerDto ownerDto = new OwnerDto();
//                ownerDto.setUserId(storeOrderDto.getPersonId());
//                List<OwnerDto> queryBuildingOwners = null;//buildingOwnerV1InnerServiceSMOImpl.queryBuildingOwners(ownerDto);
//                if (queryBuildingOwners == null || queryBuildingOwners.size() < 1) {
//                    throw new IllegalArgumentException("此商品需要身份证信息，请先完善用户信息");
//                }
//                param.put("idCard", queryBuildingOwners.get(0).getIdCard());
            }
            param.put("thirdPartyOrderNo", storeOrderDto.getOrderId());
            param.put("itemId", storeOrderCartDto.getExtValueId());
            param.put("customerName", addressDto.getUsername());
            param.put("customerPhoneNumber", addressDto.getTel());
            param.put("payType", "1");// 0-余额;1-授信;
            param.put("quantity", storeOrderCartDto.getCartNum());
            param.put("address", addressDto.getAddress());
            JSONObject checkData = JSONObject.parseObject(LlkFactory.post(URL_GET_CHECKCREATEORDER, param, chainSupplierDto, outRestTemplate));
            if (checkData.getInteger("code") != 200) {
                return new ResultVo(ResultVo.CODE_ERROR, returnData.getString("productTitle") + checkData.getString("message"));
            }
        }
        return new ResultVo(ResultVo.CODE_OK, "联联看商品可售。");
    }

    @Override
    public ResultVo notifyChainOrder(StoreOrderDto storeOrderDto, List<StoreOrderCartDto> storeOrderCartDtos, ChainSupplierDto chainSupplierDto) throws Exception {
        System.out.println("--------------------------------联联异步下单下单下单通知付款成功后--------------------------------------------");


        //获取订单收货地址URL_CREATEORDER
        StoreOrderAddressDto storeOrderAddressDto = new StoreOrderAddressDto();
        storeOrderAddressDto.setOrderId(storeOrderDto.getOrderId());
        List<StoreOrderAddressDto> userAddressDtos = storeOrderAddressInnerServiceSMOImpl.queryStoreOrderAddresss(storeOrderAddressDto);
        Assert.listOnlyOne(userAddressDtos, "未找到收货人信息");
        //获取收货地址，其中没有 省市区街道信息，再查一边
        StoreOrderAddressDto addressDto = userAddressDtos.get(0);
        AreaDto areaDto = new AreaDto();
        areaDto.setAreaCode(addressDto.getAreaCode());
        List<AreaDto> areaDtos = areaInnerServiceSMO.getWholeArea(areaDto);
        if (areaDtos.size() != 4) {//查出来的省 市 区 街道 四个长度
            return new ResultVo(ResultVo.CODE_ERROR, "省市区街道信息不完整");
        }


        for (StoreOrderCartDto storeOrderCartDto : storeOrderCartDtos) {
            if (storeOrderCartDto.getExtValueId() != null && storeOrderCartDto.getExtValueId().length() > 0) {
                String snOrderId = "LLK" + GenerateCodeFactory.getGeneratorId(GenerateCodeFactory.CODE_PREFIX_buyId);//联联看供应链商品ID
                JSONObject param = new JSONObject();
                param.put("productId", storeOrderCartDto.getProductId());
                JSONObject returnData = JSONObject.parseObject(LlkFactory.post(URL_GET_PRODUCTDETAIL, param, chainSupplierDto, outRestTemplate));
                String isneedId = returnData.getString("orderShowIdCard");
                if (isneedId.equals("1")) {//需要身份证信息
//                    OwnerDto ownerDto = new OwnerDto();
//                    ownerDto.setUserId(storeOrderDto.getPersonId());
//                    List<OwnerDto> queryBuildingOwners = null;//buildingOwnerV1InnerServiceSMOImpl.queryBuildingOwners(ownerDto);
//                    if (queryBuildingOwners == null || queryBuildingOwners.size() < 1) {
//                        throw new IllegalArgumentException("此商品需要身份证信息，请先完善用户信息");
//                    }
//                    param.put("idCard", queryBuildingOwners.get(0).getIdCard());
                }
                param.put("thirdPartyOrderNo", storeOrderDto.getOrderId());
                param.put("itemId", storeOrderCartDto.getExtValueId());
                param.put("customerName", addressDto.getUsername());
                param.put("customerPhoneNumber", addressDto.getTel());
                param.put("payType", "1");// 0-余额;1-授信;
                param.put("quantity", storeOrderCartDto.getCartNum());
                param.put("address", addressDto.getAddress());
                JSONObject checkData = JSONObject.parseObject(LlkFactory.post(URL_GET_CHECKCREATEORDER, param, chainSupplierDto, outRestTemplate));
                if (checkData.getInteger("code") == 200) {
                    StoreOrderCartPo storeOrderCartPo = new StoreOrderCartPo();
                    storeOrderCartPo.setCartId(storeOrderCartDto.getCartId());
                    storeOrderCartPo.setOrderId(storeOrderCartDto.getOrderId());
                    storeOrderCartPo.setOrderSn(snOrderId);
                    storeOrderCartInnerServiceSMOImpl.updateStoreOrderCart(storeOrderCartPo);
                } else {
                    return new ResultVo(ResultVo.CODE_ERROR, returnData.getString("productTitle") + checkData.getString("message"));
                }
            }
        }
        return new ResultVo(ResultVo.CODE_OK, "供应链商品下单成功。");
    }

    @Override
    public ResultVo queryProducts(ChainSupplierProductDto chainSupplierProductDto, ChainSupplierDto chainSupplierDto) throws Exception {
        int page = chainSupplierProductDto.getPage();
        int row = chainSupplierProductDto.getRow();
        int count = 0;
        int totalPages;//总页数

        JSONObject param = new JSONObject();
        param.put("pageIndex", page);
        param.put("pageSize", row);
        param.put("title", chainSupplierProductDto.getProdName());
        if (!StringUtil.isEmpty(chainSupplierProductDto.getCatalogId())) {//插入本地查询配置的产品类型
            ChainSupplierCatalogDto chainSupplierCatalogDto = new ChainSupplierCatalogDto();
            chainSupplierCatalogDto.setCatalogId(chainSupplierProductDto.getCatalogId());
            List<ChainSupplierCatalogDto> queryChainSupplierCatalogs = chainSupplierCatalogV1InnerServiceSMO.queryChainSupplierCatalogs(chainSupplierCatalogDto);
            Map map = new HashMap();
            if (queryChainSupplierCatalogs.size() > 0) {//查询分类
                String[] keyValues = queryChainSupplierCatalogs.get(0).getIntfUrlParam().split("&");
                for (int i = 0; i < keyValues.length; i++) {
                    String key = keyValues[i].substring(0, keyValues[i].indexOf("="));
                    String value = keyValues[i].substring(keyValues[i].indexOf("=") + 1);
                    map.put(key, value);
                }
            }
            if (map.get("productCategoryId") != null) {
                param.put("productCategoryId", map.get("productCategoryId").toString().trim());
            }
            if (map.get("type") != null) {
                param.put("type", map.get("type").toString().trim());
            }
            if (map.get("locationId") != null) {
                param.put("locationId", map.get("locationId").toString().trim());
            }
            if (map.get("city") != null) {
                param.put("city", map.get("city").toString().trim());
            }
        }

        JSONObject _returnData = JSONObject.parseObject(LlkFactory.post(URL_GET_PRODUCTS, param, chainSupplierDto, outRestTemplate));
        totalPages = _returnData.getIntValue("rowCount") / row;
        if (_returnData.getIntValue("rowCount") % row != 0) {
            totalPages++;
        }
        JSONArray products = _returnData.getJSONArray("data");
        List<ChainProductDto> chainProductDtos = new ArrayList<>();
        for (int productIndex = 0; productIndex < products.size(); productIndex++) {
            ChainProductDto productDto = new ChainProductDto();
            productDto.setProductId(products.getJSONObject(productIndex).getString("id"));
            productDto.setCsId(chainSupplierDto.getCsId());
            productDto.setCoverPhoto(products.getJSONObject(productIndex).getString("faceImg"));
            productDto.setCatalogName(products.getJSONObject(productIndex).getString("categoryName"));
            productDto.setProdName(products.getJSONObject(productIndex).getString("productTitle"));
            productDto.setState("2002");
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            productDto.setCreateTime(new Date(Long.parseLong(String.valueOf(products.getJSONObject(productIndex).getString("validBeginDate")))));
            JSONArray _proValueDatas = products.getJSONObject(productIndex).getJSONArray("items");
            List<ChainProductValueDto> chainProductValueDtos = new ArrayList<>();
            for (int valueIndex = 0; valueIndex < _proValueDatas.size(); valueIndex++) {
                ChainProductValueDto valueDto = new ChainProductValueDto();
                valueDto.setProductId(_proValueDatas.getJSONObject(valueIndex).getString("id"));
                valueDto.setCsId(chainSupplierDto.getCsId());
                valueDto.setSpecName("套餐名称");
                valueDto.setSpecValue(_proValueDatas.getJSONObject(valueIndex).getString("subTitle"));
                valueDto.setPrice(_proValueDatas.getJSONObject(valueIndex).getString("salePrice"));
                chainProductValueDtos.add(valueDto);
            }
            productDto.setChainProductValueDtos(chainProductValueDtos);
            chainProductDtos.add(productDto);
        }
        ResultVo resultVo = new ResultVo(totalPages, count, chainProductDtos);
        return resultVo;
    }


    /**
     * <p>查询单个商品信息</p>
     *
     * @param chainSupplierProductDto 订单调用链数据
     * @return RoomDto 对象数据
     */
    @Override
    public ResultVo querySingleProduct(ChainSupplierProductDto chainSupplierProductDto, ChainSupplierDto chainSupplierDto) throws Exception {
        //商品详情
        ResultVo resultVo;
        if (!StringUtil.isEmpty(chainSupplierProductDto.getProductId())) {
            JSONObject param = new JSONObject();
            param.put("productId", chainSupplierProductDto.getProductId());
            JSONObject returnData = JSONObject.parseObject(LlkFactory.post(URL_GET_PRODUCTDETAIL, param, chainSupplierDto, outRestTemplate));
            ChainProductDto productDto = new ChainProductDto();
            productDto.setProductId(returnData.getString("id"));
            productDto.setCsId(chainSupplierDto.getCsId());
            productDto.setCoverPhoto(returnData.getString("faceImg"));
            productDto.setCatalogName(returnData.getString("productTitle"));
            productDto.setProdName(returnData.getString("productTitle"));
            productDto.setUnitName(returnData.getString("faceImg"));
            productDto.setState("2002");
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            productDto.setCreateTime(new Date(Long.parseLong(String.valueOf(returnData.getString("validBeginDate")))));
            JSONArray _proValueDatas = returnData.getJSONArray("items");
            List<ChainProductValueDto> chainProductValueDtos = new ArrayList<>();
            for (int valueIndex = 0; valueIndex < _proValueDatas.size(); valueIndex++) {
                ChainProductValueDto valueDto = new ChainProductValueDto();
                valueDto.setProductId(_proValueDatas.getJSONObject(valueIndex).getString("id"));
                valueDto.setCsId(chainSupplierDto.getCsId());
                valueDto.setSpecName("套餐名称");
                valueDto.setSpecValue(_proValueDatas.getJSONObject(valueIndex).getString("subTitle"));
                valueDto.setPrice(_proValueDatas.getJSONObject(valueIndex).getString("salePrice"));
                chainProductValueDtos.add(valueDto);
            }
            productDto.setChainProductValueDtos(chainProductValueDtos);
            resultVo = new ResultVo(0, 0, productDto);
        } else {
            resultVo = new ResultVo(0, 0, null);
        }
        return resultVo;
    }

    ;


    /**
     * <p>获取评论信息</p>
     *
     * @param chainSupplierProductDto 订单调用链数据
     * @return RoomDto 对象数据
     */
    @Override
    public ResultVo queryComments(ChainSupplierProductDto chainSupplierProductDto, ChainSupplierDto chainSupplierDto) throws Exception {
        return new ResultVo(0, 0, "联联看商品不提供商品评论接口");
    }

    ;


    /**
     * <p>查询物流信息</p>
     *
     * @param chainSupplierProductDto 订单调用链数据
     * @return RoomDto 对象数据
     */
    @Override
    public ResultVo queryLogisticsInfo(ChainSupplierProductDto chainSupplierProductDto, ChainSupplierDto chainSupplierDto) throws Exception {
        ResultVo resultVo;
        JSONObject param = new JSONObject();
        param.put("orderId", "200220059906");
        JSONObject returnData = JSONObject.parseObject(LlkFactory.post(URL_GET_ORDEREXPRESS, param, chainSupplierDto, outRestTemplate));
        resultVo = new ResultVo(0, 0, returnData);
        return resultVo;
    }

    ;

    /**
     * <p>将供应链商品信息写入店铺信息</p>
     *
     * @param chainSupplierProductDto
     * @return RoomDto 对象数据
     */
    @Override
    public ResultVo insertSingleProduct(ChainSupplierProductDto chainSupplierProductDto, ChainSupplierDto chainSupplierDto) throws Exception {

        String shopId = chainSupplierProductDto.getShopId();
        String storeId = chainSupplierProductDto.getStoreId();
        String groupId = chainSupplierProductDto.getGroupId();
        String ruleId = chainSupplierProductDto.getRuleId();

        ChainSupplierCatalogDto chainSupplierCatalogDto = new ChainSupplierCatalogDto();
        chainSupplierCatalogDto.setCatalogId(groupId);
        List<ChainSupplierCatalogDto> queryChainSupplierCatalogs = chainSupplierCatalogV1InnerServiceSMO.queryChainSupplierCatalogs(chainSupplierCatalogDto);

        if (queryChainSupplierCatalogs.size() > 0) {//查询分类
            Map map = new HashMap();
            String[] keyValues = queryChainSupplierCatalogs.get(0).getIntfUrlParam().split("&");
            for (int i = 0; i < keyValues.length; i++) {
                String key = keyValues[i].substring(0, keyValues[i].indexOf("="));
                String value = keyValues[i].substring(keyValues[i].indexOf("=") + 1);
                map.put(key, value);
            }
            groupId = map.get("productCategoryId").toString().trim();
        } else {
            groupId = "";
        }
        ProductDto productDto = new ProductDto();
        productDto.setExtProdId(chainSupplierProductDto.getProductId());
        productDto.setCsId(chainSupplierProductDto.getCsId());
        int i = productInnerServiceSMOImpl.queryProductsCount(productDto);
        if (i > 0) {
            return new ResultVo(ResultVo.CODE_ERROR, "已经存在该商品信息");
        }
        ApiClient apiClient = new ApiClient(chainSupplierDto.getAppId(), chainSupplierDto.getAppSecure());
        apiClient.setDebug(true); //设置调试模式

        //商品详情
        JSONObject param = new JSONObject();
        param.put("productId", chainSupplierProductDto.getProductId());
        JSONObject productData = JSONObject.parseObject(LlkFactory.post(URL_GET_PRODUCTDETAIL, param, chainSupplierDto, outRestTemplate));

        //查询产品规格没有便插入
        ProductCategoryDto productCategoryDto = new ProductCategoryDto();
        productCategoryDto.setShopId(shopId);
        productCategoryDto.setCategoryId(groupId);
        //productCategoryDto.setCategoryName(groupApiList.get(0).getName()); //"聚合供应链");
        productCategoryDto.setStatusCd("0");
        List<ProductCategoryDto> productCategoryDtos = productCategoryInnerServiceSMOImpl.queryProductCategorys(productCategoryDto);
        productCategoryDto = new ProductCategoryDto();
        if (productCategoryDtos.size() > 0) {
            productCategoryDto = productCategoryDtos.get(0);
        } else {
            param = new JSONObject();
            param.put("eCommerce", "0");
            param.put("levelRelationship", "0");
            JSONArray categoryData = JSONObject.parseArray(LlkFactory.post(URL_GET_PRODUCTCATEGORY, param, chainSupplierDto, outRestTemplate));
            ProductCategoryPo productCategoryPo = new ProductCategoryPo();
            for (int k = 0; k < categoryData.size(); k++) {
                JSONObject category = categoryData.getJSONObject(k);
                if (category.getString("id").equals(groupId)) {
                    productCategoryPo.setCategoryId(groupId);    //GenerateCodeFactory.getGeneratorId(GenerateCodeFactory.CODE_PREFIX_categoryId));
                    productCategoryPo.setCategoryName(category.getString("name"));  //"聚合供应链");
                    productCategoryPo.setCateType("1");
                    productCategoryPo.setCategoryLevel("1");
                    productCategoryPo.setParentCategoryId("-1");
                    productCategoryPo.setStoreId(storeId);
                    productCategoryPo.setSeq("20");     //排序要找到一个合适的方法
                    productCategoryPo.setIsShow("Y");
                    productCategoryPo.setShopId(shopId);
                    int flag = productCategoryInnerServiceSMOImpl.saveProductCategory(productCategoryPo);
                    if (flag < 1) {
                        return new ResultVo(ResultVo.CODE_ERROR, "供应链分组保存失败。");
                    }
                }
            }
            productCategoryDto.setCategoryId(productCategoryPo.getCategoryId());
            productCategoryDto.setCategoryName(productCategoryPo.getCategoryName());
        }
        //商品仓库信息
        ShopHouseDto shopHouse = new ShopHouseDto();
        shopHouse.setShopId(shopId);
        shopHouse.setShName("供应链云仓");
        shopHouse.setStatusCd("0");
        List<ShopHouseDto> shopHouseList = shopHouseInnerServiceSMOImpl.queryShopHouses(shopHouse);
        shopHouse = new ShopHouseDto();
        if (shopHouseList.size() > 0) {
            shopHouse = shopHouseList.get(0);
        } else {
            ShopHousePo shopHousePo = new ShopHousePo();
            shopHousePo.setShId(GenerateCodeFactory.getGeneratorId(GenerateCodeFactory.CODE_PREFIX_shId));
            shopHousePo.setShName("供应链云仓");
            shopHousePo.setShopId(shopId);
            shopHousePo.setShDesc("供应链云仓");
            shopHousePo.setShType("2807");//普通仓库
            int flag = shopHouseInnerServiceSMOImpl.saveShopHouse(shopHousePo);
            if (flag < 1) {
                return new ResultVo(ResultVo.CODE_ERROR, "供应链仓库保存失败。");
            }
            shopHouse.setShId(shopHousePo.getShId());
            shopHouse.setShName(shopHousePo.getShName());
        }

        //商品信息
        ProductPo productPo = new ProductPo();
        productPo.setProdName(productData.getString("productTitle"));
        productPo.setUnitName("周边");
        productPo.setKeyword(productData.getString("onlyName"));
        productPo.setProdDesc(productData.getString("shareText"));  //getDescription());    //描述因为是图片改成Title
        productPo.setCategoryId(productCategoryDto.getCategoryId());
        productPo.setShId(shopHouse.getShId());
        productPo.setShName(shopHouse.getShName());
        productPo.setShopId(shopId);
        productPo.setStoreId(storeId);
        productPo.setProductId(GenerateCodeFactory.getGeneratorId(GenerateCodeFactory.CODE_PREFIX_productId));     //;//改成供应链商品ID
        productPo.setBarCode(productData.getString("id") + "");       //这里须要修改为SPU_ID
        productPo.setIsPostage("2");
        productPo.setSort("8");
        productPo.setState("2002");
        productPo.setWarnStock("50");
        productPo.setExtProdId(productData.getString("id") + "");
        productPo.setCsId(chainSupplierDto.getCsId());
        productPo.setSuType(chainSupplierDto.getSuType());
        int flag = productInnerServiceSMOImpl.saveProduct(productPo);
        //关键词处理
        doSavakeywords(productPo);
        if (flag < 1) {
            return new ResultVo(ResultVo.CODE_ERROR, "关键词保存失败。");
        }
        //保存商品封面
        doSavaSupplyFile(productData.getString("faceImg"), productPo, FileRelDto.REL_TYPE_CD_GOODS_COVER);
        JSONArray _loopImgs = productData.getJSONArray("loopImg");
        for (int valueIndex = 0; valueIndex < _loopImgs.size(); valueIndex++) {
            doSavaSupplyFile(_loopImgs.getJSONObject(valueIndex).getString("url"), productPo, FileRelDto.REL_TYPE_CD_GOODS_CAROUSEL_FIGURE);
        }

        JSONArray _proValueDatas = productData.getJSONArray("items");
        for (int valueIndex = 0; valueIndex < _proValueDatas.size(); valueIndex++) {//联联看商品有多种规格，需要和系统对接上
            //保存商品规格
            ProductSpecPo productSpecPo = new ProductSpecPo();
            productSpecPo.setSpecName(_proValueDatas.getJSONObject(valueIndex).getString("subTitle"));
            productSpecPo.setSpecId(GenerateCodeFactory.getGeneratorId(GenerateCodeFactory.CODE_PREFIX_specId));
            productSpecPo.setShopId(shopId);
            productSpecPo.setStoreId(storeId);
            flag = productSpecInnerServiceSMOImpl.saveProductSpec(productSpecPo);
            if (flag < 1) {
                return new ResultVo(ResultVo.CODE_ERROR, _proValueDatas.getJSONObject(valueIndex).getString("subTitle") + "规格保存失败");
            }
            ProductSpecDetailPo productSpecDetailPo = new ProductSpecDetailPo();
            productSpecDetailPo.setShopId(shopId);
            productSpecDetailPo.setStoreId(storeId);
            productSpecDetailPo.setDetailName("1");
            productSpecDetailPo.setDetailValue("");
            productSpecDetailPo.setDetailId(GenerateCodeFactory.getGeneratorId(GenerateCodeFactory.CODE_PREFIX_detailId));
            productSpecDetailPo.setStoreId(productSpecPo.getStoreId());
            productSpecDetailPo.setSpecId(productSpecPo.getSpecId());
            flag = productSpecDetailInnerServiceSMOImpl.saveProductSpecDetail(productSpecDetailPo);
            if (flag < 1) {
                return new ResultVo(ResultVo.CODE_ERROR, _proValueDatas.getJSONObject(valueIndex).getString("subTitle") + "保存规格值失败");
            }
            ProductSpecValuePo productSpecValuePo = new ProductSpecValuePo();
            productSpecValuePo.setValueId(GenerateCodeFactory.getGeneratorId(GenerateCodeFactory.CODE_PREFIX_valueId));
            productSpecValuePo.setSpecId(productSpecPo.getSpecId());
            productSpecValuePo.setProductId(productPo.getProductId());
            productSpecValuePo.setStock(_proValueDatas.getJSONObject(valueIndex).getString("itemChannelStock"));//库存
            productSpecValuePo.setSales(_proValueDatas.getJSONObject(valueIndex).getString("itemChannelSaleAmount"));//销量


            /*            {
                "id": 25, //套餐id
                    "subTitle": "测试套餐", //套餐名称
                    "itemChannelStock": 0, //套餐渠道库存
                    "channelPrice": 1000, //结算价(分)
                    "itemChannelSaleAmount": 0, //套餐渠道销量
                    "salePrice": 3600, //套餐售价(分)
                    "originPrice": 6000, //原价(分)
                    "memo": "备注-说明",
                    "singleMax": 10 //单次多大购买数量
                "codeAmount": 1 //发码方式  1-一单发一码; 大于1 一单发多码(当前大于1的值决定一单的发码数量)
            }*/


            productSpecValuePo.setIsDefault("T");
            productSpecValuePo.setShopId(shopId);
            productSpecValuePo.setBarCode(productData.getString("id") + "");
            productSpecValuePo.setWillExpire("0");
            productSpecValuePo.setAttrition("0");
            productSpecValuePo.setStoreId(storeId);
            productSpecValuePo.setExtValueId(_proValueDatas.getJSONObject(valueIndex).getString("id"));
            if (!StringUtil.isEmpty(ruleId)) {
                ProductPriceRuleDto productPriceRuleDto = new ProductPriceRuleDto();
                productPriceRuleDto.setRuleId(ruleId);
                List<ProductPriceRuleDto> productPriceRuleDtos = productPriceRuleV1InnerServiceSMOImpl.queryProductPriceRules(productPriceRuleDto);
                List<ProductSpecValueDto> productSpecValueDtos = new ArrayList<>();
                ProductSpecValueDto specValueDto = new ProductSpecValueDto();
            /*
                ├─ market_price	    number	是		市场价（单位：分）
                ├─ guide_price	    number	是		指导价（单位：分）
                ├─ activity_price	number	是		营销价（单位：分）
                ├─ sale_price	    number	是		销售价（单位：分）
                ├─ cost_price	    number	是		成本价（单位：分）
                ├─ 只有京东有营销价，所以没有营销价就用指导价代替
            */

            /*            {
                "id": 25, //套餐id
                    "subTitle": "测试套餐", //套餐名称
                    "itemChannelStock": 0, //套餐渠道库存
                    "channelPrice": 1000, //结算价(分)
                    "itemChannelSaleAmount": 0, //套餐渠道销量
                    "salePrice": 3600, //套餐售价(分)
                    "originPrice": 6000, //原价(分)
                    "memo": "备注-说明",
                    "singleMax": 10 //单次多大购买数量
                "codeAmount": 1 //发码方式  1-一单发一码; 大于1 一单发多码(当前大于1的值决定一单的发码数量)
            }*/
                specValueDto.setPrice((Integer.parseInt(_proValueDatas.getJSONObject(valueIndex).getString("salePrice")) * 0.01) + "");                //销售价（单位：分）
                specValueDto.setCostPrice((Integer.parseInt(_proValueDatas.getJSONObject(valueIndex).getString("salePrice")) * 0.01) + "");            //成本价（单位：分）
                specValueDto.setVipPrice((Integer.parseInt(_proValueDatas.getJSONObject(valueIndex).getString("salePrice")) * 0.01) + "");         //营销价（单位：分）
                specValueDto.setOtPrice((Integer.parseInt(_proValueDatas.getJSONObject(valueIndex).getString("salePrice")) * 0.01) + "");            //市场价（单位：分）
                specValueDto.setOwnerPrice((Integer.parseInt(_proValueDatas.getJSONObject(valueIndex).getString("salePrice")) * 0.01) + "");       //业主价（单位：分）
                specValueDto.setDeduction((Integer.parseInt(_proValueDatas.getJSONObject(valueIndex).getString("salePrice")) * 0.01) + "");          //物业抵扣金（单位：分）

                productSpecValueDtos.add(specValueDto);
                productPriceRuleDtos.get(0).setProductSpecValueDtos(productSpecValueDtos);
                List<ProductSpecValueDto> tmpProductSpecValueDtos = productPriceRuleV1InnerServiceSMOImpl.computeProductSpecValuePrices(productPriceRuleDtos.get(0));
                productSpecValuePo.setPrice(tmpProductSpecValueDtos.get(0).getPrice());                 //销售价（单位：分）
                productSpecValuePo.setCostPrice(tmpProductSpecValueDtos.get(0).getCostPrice());         //成本价（单位：分）
                productSpecValuePo.setVipPrice(tmpProductSpecValueDtos.get(0).getVipPrice());           //营销价（单位：分）
                productSpecValuePo.setOtPrice(tmpProductSpecValueDtos.get(0).getOtPrice());             //市场价（单位：分）
                productSpecValuePo.setDeduction(tmpProductSpecValueDtos.get(0).getDeduction());         //物业抵扣金（单位：分）
                productSpecValuePo.setOwnerPrice(tmpProductSpecValueDtos.get(0).getOwnerPrice());       //业主价（单位：分）
            } else {
                productSpecValuePo.setPrice((Integer.parseInt(_proValueDatas.getJSONObject(valueIndex).getString("salePrice")) * 0.01) + "");    //销售价（单位：分）
                productSpecValuePo.setCostPrice((Integer.parseInt(_proValueDatas.getJSONObject(valueIndex).getString("salePrice")) * 0.01) + ""); //成本价（单位：分）
                productSpecValuePo.setVipPrice((Integer.parseInt(_proValueDatas.getJSONObject(valueIndex).getString("salePrice")) * 0.01) + "");         //营销价（单位：分）
                productSpecValuePo.setOtPrice((Integer.parseInt(_proValueDatas.getJSONObject(valueIndex).getString("salePrice")) * 0.01) + "");            //市场价（单位：分）
                productSpecValuePo.setOwnerPrice((Integer.parseInt(_proValueDatas.getJSONObject(valueIndex).getString("salePrice")) * 0.01) + "");       //业主价（单位：分）
                productSpecValuePo.setDeduction((Integer.parseInt(_proValueDatas.getJSONObject(valueIndex).getString("salePrice")) * 0.01) + "");          //物业抵扣金（单位：分）
            }
            flag = productSpecValueInnerServiceSMOImpl.saveProductSpecValue(productSpecValuePo);
            if (flag < 1) {
                throw new IllegalArgumentException("保存价格失败");
            }
        }
        //这里是店铺列表信息，存到商品详情中
        JSONArray _proShopDatas = productData.getJSONArray("shops");
        String prodesc = "";
        for (int valueIndex = 0; valueIndex < _proShopDatas.size(); valueIndex++) {
            prodesc += "商家店铺列表：+<br>";
            prodesc += _proShopDatas.getJSONObject(valueIndex).getString("name") + "<br>";
            prodesc += _proShopDatas.getJSONObject(valueIndex).getString("address") + "<br>";
            prodesc += _proShopDatas.getJSONObject(valueIndex).getString("phoneNumber") + "<br>";
            prodesc += "<br><br>";
        }
        //   "address": "高新区天府三街69号", //商家地址
        //    "tel": "电话:1234567", //商家电话
        /*"beginTime": null, //抢购开始时间（可能为null）
                "endTime": 1606622846000, //抢购结束时间
                "validBeginDate": null, //购买后——有效开始时间（可能为null）
                "validEndDate": 1606579200000, //购买后——有效结束时间*/

        prodesc += productData.getString("address");
        ProductDetailPo productDetailPo = new ProductDetailPo();
        productDetailPo.setShopId(shopId);
        productDetailPo.setStoreId(storeId);
        productDetailPo.setContent(prodesc);
        productDetailPo.setProductId(productPo.getProductId());
        productDetailPo.setDetailId(GenerateCodeFactory.getGeneratorId(GenerateCodeFactory.CODE_PREFIX_detailId));

        flag = productDetailInnerServiceSMOImpl.saveProductDetail(productDetailPo);
        if (flag < 1) {
            throw new IllegalArgumentException("保存规格失败");
        }
        return new ResultVo(ResultVo.CODE_OK, "供应链商品保存成功。");
    }

    @Override
    public ResultVo callBackChainProduct(String param, ChainSupplierDto tmpChainSupplierDto) {
        JSONObject reqJson = JSONObject.parseObject(param);
        int type = reqJson.getIntValue("type");
        String productId = reqJson.getString("productId");
        JSONArray items = reqJson.getJSONArray("items");
        switch (type) {
            case 0:
                uderCarriage(productId); // 商品下架
                break;
            case 1:
                onSale(productId);
                break;
            case 2:
                productEmpty(items);

                break;


        }
        return new ResultVo(ResultVo.CODE_OK, ResultVo.MSG_OK);
    }

    private void productEmpty(JSONArray items) {

        String itemId = "";
        for (int itemIndex = 0; itemIndex < items.size(); itemIndex++) {
            itemId = items.getString(itemIndex);

            ProductSpecValueDto productSpecValueDto = new ProductSpecValueDto();
            productSpecValueDto.setExtValueId(itemId);
            productSpecValueDto.setStock("0");
            productSpecValueInnerServiceSMOImpl.queryProductSpecValues(productSpecValueDto);
        }
    }


    /**
     * 上架
     *
     * @param goodsId
     */
    private void onSale(String goodsId) {

        String gId = goodsId;

        // 检查商品是否上架
        ProductDto productDto = new ProductDto();
        productDto.setExtProdId(gId);
        productDto.setState(ProductDto.STATE_ON);
        List<ProductDto> productDtos = productInnerServiceSMOImpl.queryProducts(productDto);
        if (productDtos != null && productDtos.size() > 0) {
            return;
        }
        productDto = new ProductDto();
        productDto.setExtProdId(gId);
        productDto.setState(ProductDto.STATE_OFF);
        productDtos = productInnerServiceSMOImpl.queryProducts(productDto);
        if (productDtos != null && productDtos.size() > 0) {
            return;
        }
        ProductPo productPo = new ProductPo();
        productPo.setProductId(productDtos.get(0).getProductId());
        productPo.setState(ProductDto.STATE_ON);
        productInnerServiceSMOImpl.updateProduct(productPo);

    }

    private void uderCarriage(String goodsId) {
        String gId = goodsId;
        // 检查商品是否上架
        ProductDto productDto = new ProductDto();
        productDto.setExtProdId(gId);
        productDto.setState(ProductDto.STATE_ON);
        List<ProductDto> productDtos = productInnerServiceSMOImpl.queryProducts(productDto);
        if (productDtos == null || productDtos.size() == 0) {
            return;
        }

        ProductPo productPo = new ProductPo();
        productPo.setProductId(productDtos.get(0).getProductId());
        productPo.setState(ProductDto.STATE_OFF);
        productInnerServiceSMOImpl.updateProduct(productPo);

    }

    /**
     * 保存关键词
     *
     * @param productPo
     */
    private void doSavakeywords(ProductPo productPo) {
        String[] keywor = productPo.getKeyword().replaceAll("；", ";").split(";");
        for (String keyword : keywor) {
            ProductServKeywordPo servKeywordPo = new ProductServKeywordPo();
            servKeywordPo.setKeywordId(GenerateCodeFactory.getGeneratorId("11"));
            servKeywordPo.setKeywordName(keyword.trim());
            servKeywordPo.setKeywordType(HousekeepingServDto.KEYWORD_PROD_TYPE_CD);
            servKeywordPo.setObjId(productPo.getProductId());
            servKeywordPo.setShopId(productPo.getShopId());
            int save = productServKeywordInnerServiceSMOImpl.saveProductServKeyword(servKeywordPo);
            if (save < 1) {
                throw new IllegalArgumentException("商品关键字保存失败");
            }
        }
    }


    private void doSavaSupplyFile(String url, ProductPo productPo, String fileTypeCd) throws Exception {
        FileDto fileDto = new FileDto();
        fileDto.setCommunityId("-1");
        fileDto.setContext(encodeImageToBase64(url));
        fileDto.setFileId(GenerateCodeFactory.getGeneratorId(GenerateCodeFactory.CODE_PREFIX_file_id));
        fileDto.setFileName(fileDto.getFileId());

        fileDto.setSuffix("jpeg");
        String fileName = fileInnerServiceSMOImpl.saveFile(fileDto);

        FileRelPo fileRelPo = new FileRelPo();
        fileRelPo.setObjId(productPo.getProductId());
        fileRelPo.setRelTypeCd(fileTypeCd);
        fileRelPo.setFileRelId(GenerateCodeFactory.getGeneratorId(GenerateCodeFactory.CODE_PREFIX_relId));
        fileRelPo.setFileRealName(fileName);
        fileRelPo.setFileSaveName(fileName);
        fileRelPo.setSaveWay(FileRelDto.SAVE_WAY_FTP);
        int save = fileRelInnerServiceSMOImpl.saveFileRel(fileRelPo);

        if (save < 1) {
            throw new IllegalArgumentException("保存供应链文件失败");
        }
    }

    //将图片文件转化为字节数组字符串，并对其进行Base64编码处理
    private String encodeImageToBase64(String imgUrl) throws Exception {
        URL url = new URL(imgUrl);
        //打开链接
        HttpURLConnection conn = null;
        try {
            conn = (HttpURLConnection) url.openConnection();
//设置请求方式为"GET"
            conn.setRequestMethod("GET");
//超时响应时间为5秒
            conn.setConnectTimeout(5 * 1000);
//通过输入流获取图片数据
            InputStream inStream = conn.getInputStream();
//得到图片的二进制数据，以二进制封装得到数据，具有通用性
            ByteArrayOutputStream outStream = new ByteArrayOutputStream();
//创建一个Buffer字符串
            byte[] buffer = new byte[1024];
//每次读取的字符串长度，如果为-1，代表全部读取完毕
            int len = 0;
//使用一个输入流从buffer里把数据读取出来
            while ((len = inStream.read(buffer)) != -1) {
//用输出流往buffer里写入数据，中间参数代表从哪个位置开始读，len代表读取的长度
                outStream.write(buffer, 0, len);
            }
//关闭输入流
            inStream.close();
            byte[] data = outStream.toByteArray();
//对字节数组Base64编码
            BASE64Encoder encoder = new BASE64Encoder();
            String base64 = encoder.encode(data);
            return base64;//返回Base64编码过的字节数组字符串
        } catch (IOException e) {
            e.printStackTrace();
            throw new Exception("图片转换失败,请联系客服!");
        }
    }
}
